/****************************************************
          File Name:48-1-writer.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 07:20:45 PM CST
*****************************************************/

/*
 * shmp->exit; shmp->status; instead of semaphore
 * more detail refer to svshm_xfr.h
 */

#include"svshm_xfr.h"

int main(int argc,char *argv[])
{
    int semid, shmid, bytes, xfrs;  // xfrs: transfers
    struct shmseg *shmp;

    shmid=shmget(SHM_KEY,sizeof(struct shmseg),IPC_CREAT|OBJ_PERMS);
    if(shmid==-1)
        err("shmget");

    shmp=shmat(shmid,NULL,0); // no flag specificed
    if(shmp==(void *)-1)
        err("shmat");

    shmp->status=true;  // initailize to ture to ensure the first run 
	shmp->exit=false;	// reader will not exit
	shmp->cnt=0;
	
    for(xfrs=0,bytes=0;;xfrs++)
    {
        if(shmp->status==true)
        {	
			bytes+=shmp->cnt;
            shmp->cnt=read(STDIN_FILENO,shmp->buf,BUF_SIZE);
            if(shmp->cnt == -1)
				err("read");
			shmp->status=false;
        }

        if(shmp->cnt==0)
		{
			shmp->exit=true;
            break;
		}
        sleep(1);
    }
	
	for(;;)
	{
		if(shmp->status==true)
		{
			if(shmdt(shmp)==-1)
				err("shmdt");
			if(shmctl(shmid,IPC_RMID,0)==-1)
				err("shmctl");
			break;
		}
		sleep(1);
	}

    fprintf(stderr,"Sent %d bytes (%d xfrs)\n", bytes, xfrs);
    exit(EXIT_SUCCESS);
}
